<template>
  <div class="user-list-page">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <div class="flex justify-between items-center">
        <div>
          <h1 class="text-2xl font-bold text-slate-800 ">用户管理</h1>
        </div>
        <el-button type="primary" @click="router.push('/admin/user/add')" class="w-[100px]">
          添加用户
        </el-button>
      </div>
    </div>
    
    <!-- 用户统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
      <el-card shadow="never" class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-blue-100 text-blue-500  ">
            <i class="el-icon-user"></i>
          </div>
          <div class="ml-4">
            <div class="text-gray-500 text-sm">总用户数</div>
            <div class="text-2xl font-bold mt-1">{{ userStats.total }}</div>
          </div>
        </div>
      </el-card>
      
      <el-card shadow="never" class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-green-100 text-green-500  ">
            <i class="el-icon-user-solid"></i>
          </div>
          <div class="ml-4">
            <div class="text-gray-500 text-sm">管理员</div>
            <div class="text-2xl font-bold mt-1">{{ userStats.admin }}</div>
          </div>
        </div>
      </el-card>
      
      <el-card shadow="never" class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-orange-100 text-orange-500  ">
            <i class="el-icon-s-custom"></i>
          </div>
          <div class="ml-4">
            <div class="text-gray-500 text-sm">普通用户</div>
            <div class="text-2xl font-bold mt-1">{{ userStats.user }}</div>
          </div>
        </div>
      </el-card>
      
      <el-card shadow="never" class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-red-100 text-red-500  ">
            <i class="el-icon-lock"></i>
          </div>
          <div class="ml-4">
            <div class="text-gray-500 text-sm">已禁用</div>
            <div class="text-2xl font-bold mt-1">{{ userStats.disabled }}</div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card class="mb-6" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="用户名/姓名/邮箱" clearable style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="全部角色" clearable style="width: 120px">
            <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="全部状态" clearable style="width: 120px">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon class="mr-1"><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon class="mr-1"><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据表格 -->
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <div class="text-lg font-medium">用户列表</div>
          <div class="flex space-x-2">
            <el-button size="small" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
            </el-button>
            <el-button size="small" @click="handleBatchDelete" :disabled="selectedUsers.length === 0" type="danger">
              批量删除
            </el-button>
            <el-button size="small" @click="handleBatchEnable" :disabled="selectedUsers.length === 0" type="success">
              批量启用
            </el-button>
            <el-button size="small" @click="handleBatchDisable" :disabled="selectedUsers.length === 0" type="warning">
              批量禁用
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="tableLoading"
        :data="userList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column label="用户信息" min-width="200">
          <template #default="scope">
            <div class="flex items-center">
              <el-avatar :size="40" :src="scope.row.avatar">
                {{ scope.row.username.charAt(0).toUpperCase() }}
              </el-avatar>
              <div class="ml-3">
                <div class="font-medium">{{ scope.row.username }}</div>
                <div class="text-gray-500 text-sm">{{ scope.row.email }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" width="120"></el-table-column>
        <el-table-column prop="role" label="角色" width="120">
          <template #default="scope">
            <el-tag 
              size="small" 
              :type="getRoleType(scope.row.role)"
            >
              {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag 
              size="small" 
              :type="scope.row.status === 1 ? 'success' : 'danger'"
            >
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="180">
          <template #default="scope">
            {{ scope.row.lastLoginTime ? formatDateTime(scope.row.lastLoginTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              text 
              @click="editUser(scope.row)"
            >
              编辑
            </el-button>

            <el-button 
              size="small" 
              text 
              :type="scope.row.status === 1 ? 'warning' : 'success'" 
              @click="toggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              text 
              type="danger" 
              @click="deleteUser(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { userAPI } from '~/services/api'
import { Search, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 设置使用管理布局
definePageMeta({
  layout: 'admin'
})

const router = useRouter()

// 表格数据
const tableLoading = ref(false)
const userList = ref([])
const selectedUsers = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 用户统计
const userStats = ref({
  total: 0,
  admin: 0,
  user: 0,
  disabled: 0
})

// 搜索表单
const searchForm = ref({
  keyword: '',
  role: '',
  status: ''
})

// 角色选项
const roleOptions = ref([
  { value: 'admin', label: '管理员' },
  { value: 'user', label: '普通用户' }
])

const statusOptions = ref([
  { value: 1, label: '启用' },
  { value: 0, label: '禁用' }
])



// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取角色类型
const getRoleType = (role) => {
  switch (role) {
    case 'admin':
      return 'warning'
    case 'user':
      return 'info'
    default:
      return 'info'
  }
}

// 加载用户数据
const loadUsers = async () => {
  tableLoading.value = true
  
  try {
    // 构建查询参数
    const queryParams = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchForm.value.keyword || undefined,
      role: searchForm.value.role || undefined,
      status: searchForm.value.status || undefined,
      sortField: 'createdAt',
      sortOrder: 'desc'
    }

    // 调用后端API
    const response = await userAPI.getUserPage(queryParams)
    
    if (response.code === 200) {
      const data = response.data
      userList.value = data.list
      total.value = data.total
    } else {
      ElMessage.error(response.message || '加载用户列表失败')
    }
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 加载用户统计信息
const loadUserStats = async () => {
  try {
    const response = await userAPI.getUserStats()
    
    if (response.code === 200) {
      userStats.value = response.data
    } else {
      ElMessage.error(response.message || '加载用户统计失败')
    }
  } catch (error) {
    console.error('加载用户统计失败:', error)
    ElMessage.error('加载用户统计失败')
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadUsers()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    keyword: '',
    role: '',
    status: ''
  }
  currentPage.value = 1
  loadUsers()
}

// 刷新数据
const handleRefresh = () => {
  loadUsers()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadUsers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadUsers()
}

// 表格选择变化
const handleSelectionChange = (val) => {
  selectedUsers.value = val
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const ids = selectedUsers.value.map(user => user.id)
    const response = await userAPI.deleteBatchUsers(ids)
    
    if (response.code === 200) {
      ElMessage.success(response.data || `成功删除 ${selectedUsers.value.length} 个用户`)
      loadUsers()
      loadUserStats()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 批量启用
const handleBatchEnable = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择要启用的用户')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要启用选中的 ${selectedUsers.value.length} 个用户吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      }
    )
    
    const ids = selectedUsers.value.map(user => user.id)
    const response = await userAPI.updateBatchStatus({ ids, status: 1 })
    
    if (response.code === 200) {
      ElMessage.success(response.data || `成功启用 ${selectedUsers.value.length} 个用户`)
      loadUsers()
      loadUserStats()
    } else {
      ElMessage.error(response.message || '批量启用失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量启用失败:', error)
      ElMessage.error('批量启用失败')
    }
  }
}

// 批量禁用
const handleBatchDisable = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择要禁用的用户')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要禁用选中的 ${selectedUsers.value.length} 个用户吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const ids = selectedUsers.value.map(user => user.id)
    const response = await userAPI.updateBatchStatus({ ids, status: 0 })
    
    if (response.code === 200) {
      ElMessage.success(response.data || `成功禁用 ${selectedUsers.value.length} 个用户`)
      loadUsers()
      loadUserStats()
    } else {
      ElMessage.error(response.message || '批量禁用失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量禁用失败:', error)
      ElMessage.error('批量禁用失败')
    }
  }
}

// 编辑用户
const editUser = (row) => {
  router.push(`/admin/user/edit/${row.id}`)
}

// 切换用户状态
const toggleStatus = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const actionText = newStatus === 1 ? '启用' : '禁用'
  
  try {
    await ElMessageBox.confirm(
      `确定要${actionText}「${row.username}」吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: actionText === '禁用' ? 'warning' : 'info',
      }
    )
    
    const response = await userAPI.updateUserStatus(row.id, newStatus)
    
    if (response.code === 200) {
      ElMessage.success(response.data || `已${actionText}「${row.username}」`)
      loadUsers()
      loadUserStats()
    } else {
      ElMessage.error(response.message || `${actionText}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('状态切换失败:', error)
      ElMessage.error('状态切换失败')
    }
  }
}

// 删除用户
const deleteUser = async (id) => {
  const user = userList.value.find(item => item.id === id)
  
  try {
    await ElMessageBox.confirm(
      `确定要删除「${user.username}」吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await userAPI.deleteUser(id)
    
    if (response.code === 200) {
      ElMessage.success(response.data || `已删除「${user.username}」`)
      loadUsers()
      loadUserStats()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 初始化
onMounted(() => {
  loadUsers()
  loadUserStats()
})
</script>

<style scoped>
/* 表格样式优化 */
:deep(.el-table) {
  --el-table-header-bg-color: var(--el-fill-color-light) !important;
  --el-table-row-hover-bg-color: rgba(0, 0, 0, 0.02) !important;
  border-radius: 8px;
  overflow: hidden;
}


:deep(.el-card__header) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}


/* 对话框样式 */
:deep(.el-dialog__header) {
  margin-right: 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding-bottom: 15px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid var(--el-border-color-lighter);
  padding-top: 15px;
}

/* 统计卡片样式 */
.stat-card {
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.05);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}
</style>